# -*- coding: utf-8 -*-

import logging
import json
from common.bank import db as bank
from common.exemgt import db as exemgt
from common.exemgt import handler as exemgt_handler
from django.views.decorators.http import require_POST, require_GET
from common.admin import db as admin_user
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import (
    utc_to_local_str
)
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

_LOGGER = logging.getLogger('hydra')

class ExeMgtView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        if query_dct['id']:
            data = exemgt.get_exemgt(query_dct['id'])
        else:
            data = {'err': 'no parameter id found'}
        return {'result': 'ok', 'data' : data}

    def post(self, req):
        file = req.FILES['file']
        details = req.POST.dict()
        if details:
            details['status'] = 0
        insertdetails = exemgt.upsert_exemgt(details)
        ret = exemgt_handler.UploadExe(file, details)
        return {'result': 'ok'}

    def patch(req): 
        _LOGGER.info('update status: %s', req.body)
        id = req.POST.dict().keys()[0]
        q_dict = json.loads(id)
        data = exemgt.get_exemgt(q_dict['id'])
        if 'status' in data:
            data['status'] = 1
            newdata = exemgt.upsert_exemgt(data)
            exemgt_handler.WriteJson(newdata)
            return newdata.as_dict()
        else:
            return {'result':'ok', 'data': data}


    def delete(self, req):
        id = req.GET.dict()['id']
        _LOGGER.info('delete exe: %s', req)
        data = exemgt.delete_exemgt(id)
        _LOGGER.info('delete exe: %s, user: %s', id, req.user_id)
        return {'result': 'ok', 'id' : id}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(ExeMgtView, self).dispatch(*args, **kwargs)

class BankExeView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        if query_dct['id']:
            data = bank.get_bank(query_dct['id'])
            return {'result': 'ok', 'data' : data}
        else:
            return err.ResourceNotFound('id {} not found'.format(req.user_id))

    @method_decorator(response_wrapper)
    @method_decorator(token_required)

    def dispatch(self, *args, **kwargs):
        return super(BankExeView, self).dispatch(*args, **kwargs)

class ExeMgtDownloadView(TemplateView):
    def download_exe(req):
        _LOGGER.info('download: %s', req)
        filename = req.GET.dict()['filename']
        zip = exemgt_handler.DownloadExe(filename)
        return zip

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(ExeMgtDownloadView, self).dispatch(*args, **kwargs)